#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______    _______   _______ #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \  |       \ |   ____| #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  | |  .--.  ||  |__     #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  | |  |  |  ||   __|     #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  | |  '--'  ||  |____     #
#|__|     | _| `._____||_______||_______| \______| \______/  |_______/ |_______|   #
#                                                                                 #
#                          Channel Management Module                             #
#                             Modular FrameWork                                 #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Adds and deletes factoids		
def factoid(globalvars, msgvars):

	# Checks for permissions
	if msgvars["features"][4]:
		if msgvars["accessperms"][5]:

			# Checks if request is to add a factoid
			if msgvars["command"][1].lower() == 'add':
	
				# Verifies required data has been inputed
				if len(msgvars["command"]) > 3:
		
					# Checks if factoid already exists
					globalvars["cursor"].execute("select factoid from factoid where chanid = %s", (msgvars["chanid"]))
					data = globalvars["cursor"].fetchall()
					found = False
					for row in data:
						if msgvars["command"][2].lower() == row[0]:
							msgvars["server"].privmsg(msgvars["destination"], "I already know about %s." % (msgvars["command"][2].lower()))
							found = True
							break
						else:
							found = False
					
					# Adds a factoid to the database
					if not found:
						globalvars["cursor"].execute("insert into factoid (chanid, factoid, fact, nickid) values (%s, %s, %s, %s)", (msgvars["chanid"], msgvars["command"][2].lower(), ' '.join(msgvars["command"][3:]), msgvars["nickid"]))
						msgvars["server"].privmsg(msgvars["destination"], "Thanks for the lesson about %s." % (msgvars["command"][2].lower()))
				
				# Sends not enough data
				else:
					msgvars["server"].privmsg(msgvars["destination"], "I need a bit more info.")
		
			# Checks if request is to delete a factoid
			elif msgvars["command"][1].lower() == 'delete':
	
				# Checks if required data has been input
				if len(msgvars["command"]) == 3:
		
					# Checks if factoid exists
					globalvars["cursor"].execute("select factoid from factoid where chanid = %s", (msgvars["chanid"]))
					data = globalvars["cursor"].fetchall()
					found = False
					for row in data:
			
						# Deletes factoid from the database
						if msgvars["command"][2].lower() == row[0]:
							found = True
							globalvars["cursor"].execute("delete from factoid where factoid = %s and chanid = %s", (msgvars["command"][2].lower(), msgvars["chanid"]))
							msgvars["server"].privmsg(msgvars["destination"], "*poof* %s is history." % (msgvars["command"][2].lower()))
							break
						else:
							found = False
					
					# Sends factoid not found
					if not found:
						msgvars["server"].privmsg(msgvars["destination"], msgvars["command"][2].lower() + " doesn't exist")

				# Sends not enough/too much data
				elif len(msgvars["command"]) < 3:
					msgvars["server"].privmsg(msgvars["destination"], "More info please.")
				
			else:
				msgvars["server"].privmsg(msgvars["destination"], "I don't know how to do that.")
	
		# Replies not authorized
		else:
			msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")
	else:
		msgvars["server"].privmsg(destination, "Sorry but that feature is disabled here.")

# Factoid handler
def findfactoid(globalvars, msgvars):

	# Gets factoid data
	if msgvars["features"][4]:
		globalvars["cursor"].execute("select factoid, fact from factoid where chanid = %s", (msgvars["chanid"]))
		data = globalvars["cursor"].fetchall()
		found = False

		# Send factoid
		for row in data:
			if row[0] == msgvars["command"][0].lower():
		
				# Checks if factoid is directed to someone
				if len(msgvars["command"]) > 2:

					# Private messages nick
					if msgvars["command"][1].lower() == '!':
						msgvars["destination"] = msgvars["channel"]
						factoid = msgvars["command"][2] + ': ' + row[1]
						found = True
	
					# Channel messages nick
					elif msgvars["command"][1].lower() == '>':
						msgvars["destination"] = msgvars["command"][2]
						factoid = row[1]
						found = True
					
					# Sends message to channel
					else:
						msgvars["destination"] = msgvars["channel"]
						factoid = row[1]
						found = True
		
				# Sends message to channel
				else:
					msgvars["destination"] = msgvars["channel"]
					factoid = row[1]
					found = True
	
		# Sends final message
		if found:
			msgvars["server"].privmsg(msgvars["destination"], factoid)
		
		# Sends factoid not found
		if not found:
			if msgvars["features"][4] > 1:
				msgvars["server"].privmsg(msgvars["destination"], "Nobody ever taught me anything about %s." % (msgvars["command"][0].lower()))
		
def autoload(globalvars):
			
	# Loads oncall
	oncall = {'factoid':factoid, 'findfactoid':findfactoid}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
	
def load(globalvars, msgvars):
			
	# Loads oncall
	oncall = {'factoid':factoid, 'findfactoid':findfactoid}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already an oncall function named %s." % (feature[0]))
	return True
			
def unload(globalvars, msgvars, reloadmodule = False):
			
	# Unloads oncall
	oncall = {'factoid':factoid, 'findfactoid':findfactoid}
	for feature in oncall.items():
		if feature[0] in globalvars["oncall"].keys():
			del globalvars["oncall"][feature[0]]
	return True
